//
//  exchangeDKEView.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/26.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyUserDefaults


class exchangeDKEView: UIView ,UIViewControllerTransitioningDelegate{
    var cancelBtn :UIButton = UIButton()
    var outerImage:UIImageView = UIImageView()
    var mywindow :UIView?
    var numberM :NSString = "";
    var exNStr :NSString = ""
    var dkeStr : NSString = ""
    var goods_idStr : NSString = ""
    var allDke : NSString = ""
    
    var whiteView :UIView = UIView()
    //背景区域的颜色和透明度
    var passwordView:CYPasswordView!
    //var passwordView:CYPasswordView!
    var backgroundColor1:UIColor  = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
    var topOrBottomViewStartFrame = CGRect.init(x: 25, y: kScreenHeight, width: kScreenWidth, height: 500)
    //初始化视图
    func initPopBackGroundView() -> UIView {
        self.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        self.backgroundColor = backgroundColor1
        self.isHidden = true
        //为落下的视图添加背景图
        let innerImage:UIImageView = UIImageView.init(frame: CGRect.init(x: 0, y: kScreenHeight - 330, width: kScreenWidth, height: 210))
        
        innerImage.image = UIImage.init(named: "inner_layerImage")
        self.addSubview(innerImage)
        
        outerImage = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        outerImage.isHidden = true
        outerImage.image = UIImage.init(named: "outer_layerImage")
        self.addSubview(outerImage)
        
        
        
        return self
    }
    override func didMoveToWindow() {
            NotificationCenter.default.addObserver(self, selector: #selector(self.forgetPassworld), name: NSNotification.Name(rawValue:"CYPasswordViewForgetPWDButtonClickNotification"), object: nil)
        
    }
    override func willMove(toWindow newWindow: UIWindow?) {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue:"CYPasswordViewForgetPWDButtonClickNotification"), object: nil)


    }
    //为白色视图添加子视图
    @objc func forgetPassworld(){
        self.passwordView.hide();
    }
    func addWhiteViewSubView() {

        let imageView: UIImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: whiteView.frame.size.width, height: whiteView.frame.size.height))
        imageView.layer.masksToBounds = true
        imageView.backgroundColor = UIColor("#2B3359")
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        imageView.image = UIImage.init(named: "bmw_image")
        imageView.isUserInteractionEnabled = true
        
        whiteView.addSubview(imageView)
        let titleLabel: UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 15, width: whiteView.frame.size.width, height: 16))
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.text = String(format: "%@%@",numberM, XALanguageManager.getString(key: "能量包"))
        titleLabel.textAlignment = .center
        
        imageView.addSubview(titleLabel)
        
        let topphoto = UIImageView()
        topphoto.layer.cornerRadius = 23;
        imageView.addSubview(topphoto)
        topphoto.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: 64, height: 64))
            make.top.equalTo(60)
        }
        topphoto.sd_setImage(with: NSURL.init(string: "")! as URL, placeholderImage: UIImage.init(named: "组 1@2x"), options: [], progress: nil, completed:nil)
        
        
        
        let contentLabel: UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 130 , width: whiteView.frame.size.width - 40, height: 16))
        contentLabel.textColor = UIColor("909090")
        contentLabel.font = UIFont.systemFont(ofSize: 15)
        contentLabel.numberOfLines = 0
        contentLabel.textAlignment = NSTextAlignment.center
        contentLabel.text = String(format: "%@ %d MT", XALanguageManager.getString(key: "Get an extra"),exNStr.intValue * numberM.intValue/100 )
        
        imageView.addSubview(contentLabel)
        
        
        
        let codeImage = UIImageView()
        codeImage.layer.cornerRadius = 23;
        imageView.addSubview(codeImage)
        codeImage.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: 0, height: 10))
            make.top.equalTo(160)
        }
        let url = "https://www.jianshu.com/u/01b7a2dd26e8oioiio";
        //你的头像（可以为nil）
        let headerImage = UIImage(named: "")
        //生成图片并且显示
        codeImage.image = setupQRCodeImage(url, image: headerImage)
//
        let Bottombutton = UIButton()
        Bottombutton.layer.cornerRadius = 20;
        imageView.addSubview(Bottombutton)
        Bottombutton.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 50, height: 44))
            make.top.equalTo(codeImage.snp.bottom).offset(15)
        }
        
        Bottombutton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        Bottombutton.backgroundColor = UIColor("#297EFB")
        Bottombutton.setTitle(String(format: "%@ %@ DKE", XALanguageManager.getString(key: "Confirmation cost"),self.dkeStr), for: .normal)
        Bottombutton.addTarget(self, action: #selector(exchangeDKEView.checkPassWorld), for: .touchUpInside)
        
        Bottombutton.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        
        let bottomLabel = UILabel()
        //        bottomLabel.layer.cornerRadius = 23;
        imageView.addSubview(bottomLabel)
        bottomLabel.font = UIFont.systemFont(ofSize: 13)
        bottomLabel.textAlignment = .center
        bottomLabel.adjustsFontSizeToFitWidth = true
        bottomLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 20, height: 17))
            make.top.equalTo(Bottombutton.snp.bottom).offset(15)
        }
        bottomLabel.text = String(format: "%@ : %@", XALanguageManager.getString(key: "您可用的DKE"),Defaults[.allDKE]!)
        bottomLabel.textColor = UIColor("#297EFB")
        //
        
        let cancelButton = UIButton(frame: CGRect(x: 15, y: 15, width: 15, height: 15))
        cancelButton.setImage(UIImage.init(named: "关  闭@2x"), for: .normal)
        imageView.addSubview(cancelButton)
        cancelButton.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        
    }
  
    
    func payAction(){
        MyNetwork.request(target: .pay_goods(user_id: Defaults[.userID]!,goods_id:self.goods_idStr as String), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                let SuccessView1: SuccessView = SuccessView()
                SuccessView1.dkeStr = self.numberM as String
                SuccessView1.topOrBottomViewStartFrame = CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth - 0, height: 480)
                SuccessView1.addAnimateFromBottom()
                
                self.passwordView.requestComplete(true, message: XALanguageManager.getString(key: "成功"))
                
                
                let time: TimeInterval = 1.0
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    //code
                    self.passwordView.stopLoading()
                    self.passwordView.hide()
                    print("1 秒后输出")
                }
                
            }else{
                self.passwordView.requestComplete(false, message: XALanguageManager.getString(key: "失败"))
                
                let time: TimeInterval = 1.0
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    //code
                    self.passwordView.stopLoading()
                    self.passwordView.hide()
                    print("1 秒后输出")
                };
//                SVProgressHUD.showError(withStatus: needModel.message)
//                self.navigationController?.view.makeToast(needModel.message)
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
           SVProgressHUD.showError(withStatus: error.localizedDescription)
        }
    }
    
    @objc func checkPassWorld(){
        // 验证密码
        passwordView = CYPasswordView();
        passwordView.title = XALanguageManager.getString(key: "输入支付密码")
        passwordView.loadingText = XALanguageManager.getString(key:"提交中...")
        passwordView.show(in: mywindow)
        
        passwordView.finish = { password in
            self.passwordView.hideKeyboard()
            self.passwordView.startLoading()
        
            MyNetwork.request(target: .checkPayPwd(user_id: Defaults[.userID]!, pay_password: String().md5(inString: password!)), success: { (result) in
                    kLog(result)
                    let needModel = BaseModel()
                    needModel.yy_modelSet(with: result as! [AnyHashable : Any])
                    
                    if needModel.code == 1111{
                        self.passwordView.hide(); self.checkNextWorld111()
                        //self.111
                    }else{
                    self.passwordView.requestComplete(false, message: XALanguageManager.getString(key: "失败"))
                        
                        let time: TimeInterval = 1.0
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                            //code
                            self.passwordView.stopLoading()
                            self.passwordView.hide()
                            print("1 秒后输出")
                        }
                    }
                    
                }) { (error) in
                    //kLog(error.localizedDescription)
                    
                }
            
            
        }
        
        
        
        
    }
    
    
    @objc func checkNextWorld111(){
        // 验证密码
        passwordView = CYPasswordView();
        passwordView.title = XALanguageManager.getString(key: "输入谷歌验证码")
        passwordView.loadingText = XALanguageManager.getString(key:"提交中...")
        passwordView.show(in: mywindow)
        
        passwordView.finish = { password in
            self.passwordView.hideKeyboard()
            self.passwordView.startLoading()
            self.nextAction111(passWorrd: password!)
        }
    }
    
    
    
    @objc func nextAction111(passWorrd :String)  {
        
        //self.phoneTextField.resignFirstResponder();
        MyNetwork.request(target: .checkYanzhengqi(user_id: Defaults[.userID]!, code :passWorrd), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                //self.zhuanChu()
                self.payAction()
            }else{
                self.passwordView.requestComplete(false, message: XALanguageManager.getString(key: "失败"))
                
                let time: TimeInterval = 1.0
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    //code
                    self.passwordView.stopLoading()
                    self.passwordView.hide()
                    print("1 秒后输出")
                }
            }
            
        }) { (error) in
            //self.navigationController?.view.makeToast(error.localizedDescription)
            self.passwordView.requestComplete(false, message: error.localizedDescription)
            
            let time: TimeInterval = 1.0
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                //code
                self.passwordView.stopLoading()
                self.passwordView.hide()
                print("1 秒后输出")
            }
            kLog(error.localizedDescription)
        }
        
    }
    func addAnimateFromBottom() {
        UIApplication.shared.keyWindow?.addSubview(self.initPopBackGroundView())
        self.isHidden = false
        self.cancelBtn.isHidden = true
        
        self.cancelBtn = UIButton.init(type: UIButtonType.custom)
        self.cancelBtn.frame = CGRect.init(x:0, y:0, width: kScreenWidth, height: kScreenHeight)
        self.cancelBtn.tag = 1
        self.cancelBtn.setImage(UIImage.init(named: "cancel_white"), for: UIControlState.normal)
        self.cancelBtn.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        self.addSubview(self.cancelBtn)
        
        
        self.whiteView.frame = topOrBottomViewStartFrame
        self.whiteView.backgroundColor = ZHFColor.zhf_colorAlpha(withHex: 0x2B3359, alpha: 0)
        self.addSubview(self.whiteView)
        addWhiteViewSubView()
        
        
        UIView.animate(withDuration:0.25, animations: {
            self.whiteView.frame.origin.y = kScreenHeight - 330
            self.bringSubview(toFront:self.outerImage)
        }) { (_) in
            UIView.animate(withDuration: 0.2, animations: {
                self.whiteView.frame.origin.y = kScreenHeight - 330
            }, completion: { (_) in
                UIView.animate(withDuration: 0.2, animations: {
                    self.whiteView.frame.origin.y = kScreenHeight - 330
                }, completion: { (_) in
                    self.cancelBtn.isHidden = false
                    
                })
            })
        }
    }
    
    @objc func cancelBtnClickTop(btn:UIButton){
        self.cancelBtn.isHidden = true
        UIView.animate(withDuration: 0.5, animations: {
            self.whiteView.frame.origin.y = -kScreenHeight
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    @objc func cancelBtnClickBottom(btn:UIButton){
        self.cancelBtn.isHidden = true
        UIView.animate(withDuration: 0.25, animations: {
            self.whiteView.frame.origin.y = kScreenHeight
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    func shareAction() {
        
    }
    func nextAction(){
        //next
    }
    
    
    
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 width: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    
}
